<script setup lang="ts">
import { IllnessTime, MsgType, PrescriptionStatus } from '@/enum'
import { flagOptions, timeOptions } from '@/services/constants'
import { useUserStore } from '@/stores'
import type { Image } from '@/types/consult'
import type { Message, Prescription } from '@/types/room'
import { ImagePreview, Toast } from 'vant'
import dayjs from 'dayjs'
import doctorAvatar from '@/assets/avatar-doctor.svg'
import { useRouter } from 'vue-router'
import EvaluateCard from './EvaluateCard.vue'
import { useLookPrescription } from '@/composable'
import { getConsultFlagText, getIllnessTimeText } from '@/utils/filter'

defineProps<{
  list: Message[]
}>()

const store = useUserStore()
const router = useRouter()

// 1. 根据值取标题
// const getIllnessTimeText = (value?: IllnessTime) => {
//   return timeOptions.find((item) => item.value === value)?.label
// }
// const getConsultFlagText = (value?: 0 | 1) => {
//   return flagOptions.find((item) => item.value === value)?.label
// }

// 2. 预览图片
const onPreviewImg = (pictures?: Image[]) => {
  if (pictures && pictures.length > 0) {
    ImagePreview(pictures?.map((item) => item.url))
  }
}

// 3. 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('HH:mm')
}

// 4. 图片真正渲染完毕
const onImgLoad = (notScroll?: boolean) => {
  // console.log('图片真正渲染出来了')
  // 判断
  if (notScroll) return
  window.scrollTo(0, document.body.scrollHeight)
}

// 5. 获取处方单
// const showPrescription = async (preId?: string) => {
//   // console.log(preId)
//   if (preId) {
//     // 5.1 发请求
//     const res = await getPrescriptionPic(preId)
//     console.log(res.data)

//     // 5.2 预览处方
//     ImagePreview([res.data.url])
//   }
// }
const { showPrescription } = useLookPrescription()

// 6. 购买药品
const buy = (pre?: Prescription) => {
  if (pre) {
    // 6.1 如果处方失效：提示即可
    if (pre.status === PrescriptionStatus.Invalid) {
      return Toast('当前处方已失效')
    }

    // 6.2 如果没付款且没订单ID：去预支付页面
    if (pre.status === PrescriptionStatus.NotPayment && !pre.orderId) {
      return router.push(`/order/pay?id=${pre.id}`)
    }

    // 6.3 如果没付款且有订单ID，代表已经生成订单没付款：去订单详情付款
    router.push(`/order/${pre.orderId}`)
  }
}
</script>

<template>
  <!-- 包裹标签 -->
  <template
    v-for="{
      id,
      msgType,
      msg,
      from,
      fromAvatar,
      createTime,
      notScroll
    } in list"
    :key="id"
  >
    <!-- 病情描述 -->
    <div class="msg msg-illness" v-if="msgType === MsgType.CardPat">
      <div class="patient van-hairline--bottom">
        <p>
          {{ msg.consultRecord?.patientInfo.name }}
          {{ msg.consultRecord?.patientInfo.genderValue }}
          {{ msg.consultRecord?.patientInfo.age }}岁
        </p>
        <p>
          {{ getIllnessTimeText(msg.consultRecord?.illnessTime) }} |
          {{ getConsultFlagText(msg.consultRecord?.consultFlag) }}
        </p>
      </div>
      <van-row>
        <van-col span="6">病情描述</van-col>
        <van-col span="18">{{ msg.consultRecord?.illnessDesc }}</van-col>
        <van-col span="6">图片</van-col>
        <van-col span="18" @click="onPreviewImg(msg.consultRecord?.pictures)"
          >点击查看</van-col
        >
      </van-row>
    </div>

    <!-- 温馨提示-通知 -->
    <div class="msg msg-tip" v-if="msgType === MsgType.NotifyTip">
      <div class="content">
        <span class="green">温馨提示：</span>
        <span>{{ msg.content }}</span>
      </div>
    </div>

    <!-- 通知 -->
    <div class="msg msg-tip" v-if="msgType === MsgType.Notify">
      <div class="content">
        <span>{{ msg.content }}</span>
      </div>
    </div>

    <!-- 发送文字  -->
    <div
      class="msg msg-to"
      v-if="msgType === MsgType.MsgText && store.user?.id === from"
    >
      <div class="content">
        <div class="time">{{ formatTime(createTime) }}</div>
        <div class="pao">{{ msg.content }}</div>
      </div>
      <van-image :src="fromAvatar" />
    </div>

    <!-- 发送图片 -->
    <div
      class="msg msg-to"
      v-if="msgType === MsgType.MsgImage && store.user?.id === from"
    >
      <div class="content">
        <div class="time">{{ formatTime(createTime) }}</div>
        <van-image
          fit="contain"
          :src="msg.picture?.url"
          @click="onPreviewImg([msg.picture as Image])"
          @load="onImgLoad(notScroll)"
        />
      </div>
      <!-- 头像 -->
      <van-image :src="fromAvatar" />
    </div>

    <!-- 接收文字 -->
    <div
      class="msg msg-from"
      v-if="msgType === MsgType.MsgText && store.user?.id !== from"
    >
      <van-image :src="doctorAvatar" />
      <div class="content">
        <div class="time">{{ formatTime(createTime) }}</div>
        <div class="pao">{{ msg.content }}</div>
      </div>
    </div>

    <!-- 接收图片 -->
    <div
      class="msg msg-from"
      v-if="msgType === MsgType.MsgImage && store.user?.id !== from"
    >
      <van-image :src="doctorAvatar" />
      <div class="content">
        <div class="time">{{ formatTime(createTime) }}</div>
        <van-image
          fit="contain"
          :src="msg.picture?.url"
          @click="onPreviewImg([msg.picture as Image])"
          @load="onImgLoad(notScroll)"
        />
      </div>
    </div>

    <!-- 处方消息 -->
    <div class="msg msg-recipe" v-if="msgType === MsgType.CardPre">
      <div class="content">
        <div class="head van-hairline--bottom">
          <div class="head-tit">
            <h3>电子处方</h3>
            <p @click="showPrescription(msg.prescription?.id)">
              原始处方 <van-icon name="arrow"></van-icon>
            </p>
          </div>
          <p>
            {{ msg.prescription?.name }}
            {{ msg.prescription?.genderValue }} {{ msg.prescription?.age }}岁
            {{ msg.prescription?.diagnosis }}
          </p>
          <p>开方时间：{{ msg.prescription?.createTime }}</p>
        </div>
        <div class="body">
          <div
            class="body-item"
            v-for="med in msg.prescription?.medicines"
            :key="med.id"
          >
            <div class="durg">
              <p>{{ med.name }} {{ med.specs }}</p>
              <p>{{ med.usageDosag }}</p>
            </div>
            <div class="num">x{{ med.quantity }}</div>
          </div>
        </div>
        <!-- 购买: 传递处方 -->
        <div class="foot">
          <span @click="buy(msg.prescription)">购买药品</span>
        </div>
      </div>
    </div>

    <!-- 评价和未评价卡片 -->
    <div
      class="msg msg-comment"
      v-if="msgType === MsgType.CardEvaForm || msgType === MsgType.CardEva"
    >
      <evaluate-card :evaluate-doc="msg.evaluateDoc"></evaluate-card>
    </div>

    <!-- 订单取消 -->
    <div
      class="msg msg-tip msg-tip-cancel"
      v-if="msgType === MsgType.NotifyCancel"
    >
      <div class="content">
        <span>{{ msg.content }}</span>
      </div>
    </div>
  </template>
</template>

<style lang="scss" scoped>
@import '@/styles/room.scss';
</style>
